package com.wisdytech.common.handler;

import com.alibaba.fastjson.JSON;
import com.wisdytech.common.bean.StandardConfigResult;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.enums.LogType;
import com.wisdytech.common.exception.ConfigurationException;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.log.model.SysLog;
import com.wisdytech.linkdcs.log.service.ISysLogService;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * 
 * <p>ClassName: ExceptionHandler</p>
 * <p>Description: 异常处理类</p>
 * <p>Author: PC</p>
 * <p>Date: 2017-10-17</p>
 */
@ControllerAdvice 
public class GlobalExceptionHandler {
    
    private Logger logger =LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    @Resource
    private ISysLogService sysLogService;
    

    @ExceptionHandler
    @ResponseBody
    public Object resolveException(HttpServletRequest request, HttpServletResponse response,
            Exception ex) {
        logger.error("系统异常",ex);
        //获取用户信息
        SysUser user = BaseUtil.getCurrentUser();
        //保存异常信息
        addSystemException(user, request, ex);
        
        //判断是否是ajax请求
        boolean isAjax =isAjax(request);
        
        if(isAjax){
            String errorMessge = "系统异常";
            String errorResponse="";
            
            if(ex instanceof ServiceException) {
                errorMessge = ex.getMessage();
                errorResponse =JSON.toJSONString(StandardResult.getFailResult(errorMessge));
            }else if(ex instanceof ConfigurationException) {//组态设计器返回值不同
            	errorResponse =JSON.toJSONString(StandardConfigResult.getErrorResult(
            			((ConfigurationException) ex).getCode(), ex.getMessage()));
            }else {
            	errorResponse =JSON.toJSONString(StandardResult.getFailResult(errorMessge));
            }
            
            return errorResponse;      
        }else{
            return new ModelAndView("redirect:/login");
        }
    }
    
    /**
     * 
     * <p>Description: 判断是否为ajax请求</p>
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request){
    	return true;
        /*if(StringUtils.isBlank(request.getHeader("X-Requested-With"))){
            return false;
        }
        return  "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()) ;*/
    }
    
    
    

    /**
     * 
     * <p>Description: 保存异常信息</p>
     */
    public void addSystemException(SysUser user,HttpServletRequest request,Exception ex){
    	
    	if(null == user) {
    		return;
    	}
        try {
        	String url = request.getRequestURI().toString();
    		String contextPath = request.getContextPath();
    		//截取url,getRequestURI方法获取的url带上下文,需要截取掉
    		url = url.substring(contextPath.length()+1);
            
            SysLog log =new SysLog();
            log.setPkId(BaseUtil.getUUID());
            log.setCreateDate(new Date());
            log.setRouteIp(BaseUtil.getIpAddress(request));
            log.setUserId(user.getPkId());
            log.setUserName(user.getUsername()); 
            log.setType(LogType.ERROR.getCode());
            
            
            StringWriter strWrit = new StringWriter();
            PrintWriter printWrit = new PrintWriter(strWrit);
            ex.printStackTrace(printWrit);
            String logConten = strWrit.toString();
            log.setRemark(logConten);
            
            sysLogService.addErrorLog(log, url);
            
            
        } catch (Exception e) {
            logger.error("保存异常数据异常",e);
        }
        
    
    }
    
    
}
